import api from '../../api'

export default {
    namespaced: true,// 是否开启命名空间
    state: {
        token: window.localStorage.getItem('token') || '',
        userData: window.localStorage.getItem('userData')?JSON.parse(window.localStorage.getItem('userData')) : {}
    },
    mutations: {
        setToken(state, token) {
            state.token = token;
            window.localStorage.setItem('token', token)
        },
        setUserData(state,data) {
            state.userData = data
            window.localStorage.setItem('userData', JSON.stringify(data))
        },
    },
    actions: {
        LOGIN(context, data) {
            return new Promise((resolve,reject) => {
                api.login(data).then(res=> {
                    if(res.code===1) {
                        context.commit('setToken', res.data.token)
                        context.commit('setUserData', res.data.data)
                        resolve(res.data)
                    } else {
                        reject(res.message)
                    }
                }).catch(err=>{
                    reject(err)
                })
            })
        }
    }
}